package com.sky.utils;

import com.alibaba.fastjson.JSON;
import com.sky.properties.WeChatProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信登录认证工具类
 * @author zgp
 * @version V1.0
 * @date 2025-01-24 21:55
 */
@Component
public class WeChatAuthUtil {
    // 微信登录API接口地址
    public static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;

    /**
     * 根据临时凭证，调用微信登录接口，获取用户唯一标识openId
     *
     * @param code wx登录临时凭证
     * @return openId 用户唯一标识
     */
    public String getOpenid(String code) {
        Map<String, String> params = new HashMap<>();
        params.put("appid", weChatProperties.getAppid());
        params.put("secret", weChatProperties.getSecret());
        params.put("js_code", code);
        params.put("grant_type", "authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN_URL, params);
        Map map = JSON.parseObject(json, Map.class);
        return map.get("openid").toString();
    }
}